/**
 * Software License, Version 1.0 Copyright 2003 The Trustees of Indiana
 * University. All rights reserved. Redistribution and use in source and binary
 * forms, with or without modification, are permitted provided that the
 * following conditions are met: 1) All redistributions of source code must
 * retain the above copyright notice, the list of authors in the original source
 * code, this list of conditions and the disclaimer listed in this license; 2)
 * All redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the disclaimer listed in this license in the
 * documentation and/or other materials provided with the distribution; 3) Any
 * documentation included with all redistributions must include the following
 * acknowledgement: "This product includes software developed by the Community
 * Grids Lab. For further information contact the Community Grids Lab at
 * http://communitygrids.iu.edu/." Alternatively, this acknowledgement may
 * appear in the software itself, and wherever such third-party acknowledgments
 * normally appear. 4) The name Indiana University or Community Grids Lab or
 * NaradaBrokering, shall not be used to endorse or promote products derived
 * from this software without prior written permission from Indiana University.
 * For written permission, please contact the Advanced Research and Technology
 * Institute ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202. 5)
 * Products derived from this software may not be called NaradaBrokering, nor
 * may Indiana University or Community Grids Lab or NaradaBrokering appear in
 * their name, without prior written permission of ARTI. Indiana University
 * provides no reassurances that the source code provided does not infringe the
 * patent or any other intellectual property rights of any other entity. Indiana
 * University disclaims any liability to any recipient for claims brought by any
 * other entity based on infringement of intellectual property rights or
 * otherwise. LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH
 * NO WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY
 * GIVES NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF
 * INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS.
 * INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS",
 * "VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.
 * LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR
 * ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION
 * GENERATED USING SOFTWARE.
 */
/**
 * Software License, Version 1.0 Copyright 2003 The Trustees of Indiana
 * University. All rights reserved. Redistribution and use in source and binary
 * forms, with or without modification, are permitted provided that the
 * following conditions are met: 1) All redistributions of source code must
 * retain the above copyright notice, the list of authors in the original source
 * code, this list of conditions and the disclaimer listed in this license; 2)
 * All redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the disclaimer listed in this license in the
 * documentation and/or other materials provided with the distribution; 3) Any
 * documentation included with all redistributions must include the following
 * acknowledgement: "This product includes software developed by the Community
 * Grids Lab. For further information contact the Community Grids Lab at
 * http://communitygrids.iu.edu/." Alternatively, this acknowledgement may
 * appear in the software itself, and wherever such third-party acknowledgments
 * normally appear. 4) The name Indiana University or Community Grids Lab or
 * NaradaBrokering, shall not be used to endorse or promote products derived
 * from this software without prior written permission from Indiana University.
 * For written permission, please contact the Advanced Research and Technology
 * Institute ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202. 5)
 * Products derived from this software may not be called NaradaBrokering, nor
 * may Indiana University or Community Grids Lab or NaradaBrokering appear in
 * their name, without prior written permission of ARTI. Indiana University
 * provides no reassurances that the source code provided does not infringe the
 * patent or any other intellectual property rights of any other entity. Indiana
 * University disclaims any liability to any recipient for claims brought by any
 * other entity based on infringement of intellectual property rights or
 * otherwise. LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH
 * NO WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY
 * GIVES NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF
 * INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS.
 * INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS",
 * "VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.
 * LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR
 * ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION
 * GENERATED USING SOFTWARE.
 */

package cgl.narada.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

/**
 * Initializaes Log4j logger and other paths for this JVM <br>
 * ONE STOP for system initialization. To set a specific NB home set the NB_HOME
 * system variable <br>
 * Created on Oct 20, 2005
 * 
 * @author Harshawardhan Gadgil (hgadgil@grids.ucs.indiana.edu)
 */
public class SystemInit {

	static Logger log = Logger.getLogger("SystemInit");
	public static final String SYS_NB_HOME = "nb.home";
	public static final String SYS_KEYSTORE = "keystore";
	public static final String SYS_SERVICE_CONFIG_PATH = "service.conf";
	public static final String SYS_BROKER_KEYSTORE = "broker.keystore";
	public static final String SYS_BROKER_CERTIFICATE_TRUSTRORE = "brokerCert.truststore";
	public static final String SYS_BROKER_KEYSTORE_PASSWORD = "keystore.password";
	public static final String SYS_BROKER_TRUSTSTORE_PASSWORD = "truststore.password";

	private static Properties myProperties = new Properties();

	private static boolean initDone = false;

	public static String getInitData(String dataId)
			throws SystemNotInitializedException {
		if (initDone)
			return myProperties.getProperty(dataId);
		else
			throw new SystemNotInitializedException(
					"System was not initialized");
	}

	public static void init() {

		if (initDone) return;

		Properties sysProps = null;
		try {
			sysProps = getEnvironmentVariables();
		}
		catch (Throwable e1) {
			System.err.println("Error getting System Properties: " + e1);
		}

		// Set default to the directory from where the jvm was inited...
		String default_NB_HOME = sysProps.getProperty("user.dir");

		String os = sysProps.getProperty("os.name").toLowerCase();
		String NB_HOME = sysProps.getProperty("NB_HOME");

		if (NB_HOME == null) NB_HOME = default_NB_HOME;

		NB_HOME = new File(NB_HOME).getAbsolutePath();
		System.out.println("Using NB_HOME: " + NB_HOME);

		myProperties.setProperty(SYS_NB_HOME, NB_HOME);

		if (new File(NB_HOME + "/config/log4j.properties").exists())
			PropertyConfigurator
					.configure(NB_HOME + "/config/log4j.properties");
		else {
			log.warn("Log4J Config [NB_HOME/config/log4j.properties] "
					+ "not found. Logging may not work correctly !");
		}

		String serviceConfigPath = new File(NB_HOME
				+ "/config/ServiceConfiguration.txt").getAbsolutePath();
		log.info("Using Service configuration: " + serviceConfigPath);
		myProperties.setProperty(SYS_SERVICE_CONFIG_PATH, serviceConfigPath);

		Properties props = new Properties();

		try {
			props.load(new FileInputStream(serviceConfigPath));
		}
		catch (Exception e) {
			log.error("" + e);
			return;
		}

		String keystore = NB_HOME + "/" + props.getProperty("SecurityKeyStore");

		log.info("Setting KeyStore: " + keystore);
		myProperties.setProperty(SYS_KEYSTORE, keystore);

		// HG: Added Mar 21, 2006
		// Set default location of broker keystore and certificate truststore
		myProperties.setProperty(SYS_BROKER_KEYSTORE, NB_HOME
				+ "/keystore/Broker.KEYSTORE");
		myProperties.setProperty(SYS_BROKER_CERTIFICATE_TRUSTRORE, NB_HOME
				+ "/keystore/Broker.TRUSTSTORE");
		myProperties.setProperty(SYS_BROKER_KEYSTORE_PASSWORD, "passpass");
		myProperties.setProperty(SYS_BROKER_TRUSTSTORE_PASSWORD, "passpass");

		// Other init in the future may similarly go in here...

		initDone = true;
	}

	/**
	 * Gets a list of Environment variables. Code from <br>
	 * <code>http://www.rgagnon.com/javadetails/java-0150.html</code><br>
	 * Visited: <code>Feb 12, 2005</code>
	 * 
	 * @return Properties Object containing the Environment Variables
	 * @throws Throwable
	 */
	private static Properties getEnvironmentVariables() throws Throwable {
		Process p = null;
		Properties envVars = new Properties();
		Runtime r = Runtime.getRuntime();
		String OS = System.getProperty("os.name").toLowerCase();

		// System.out.println(OS);
		if (OS.indexOf("windows 9") > -1) {
			p = r.exec("command.com /c set");
		}
		else if ((OS.indexOf("nt") > -1) || (OS.indexOf("win") > -1)) {
			// thanks to JuanFran for the xp fix!
			p = r.exec("cmd.exe /c set");
		}
		else {
			// our last hope, we assume Unix (thanks to H. Ware for the fix)
			p = r.exec("env");
		}
		BufferedReader br = new BufferedReader(new InputStreamReader(p
				.getInputStream()));
		String line;
		while ((line = br.readLine()) != null) {
			int idx = line.indexOf('=');
			String key = line.substring(0, idx);
			String value = line.substring(idx + 1);
			envVars.setProperty(key, value);
			// System.out.println("GOT <" + key + "> ->" + value);
		}

		Properties sysProps = System.getProperties();
		for (Enumeration e = sysProps.keys(); e.hasMoreElements();) {
			String key = (String) e.nextElement();
			String value = sysProps.getProperty(key);
			envVars.put(key, value);
			// System.out.println("GOT <" + key + "> ->" + value);
		}
		return envVars;
	}

	/**
	 * TESTING Purposes only
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		SystemInit.init();
	}

}
